package com.ukao.cashregister.ui.sendFactory;


import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gprinterio.GpDevice;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.BatchDetailsAdapter;
import com.ukao.cashregister.base.IAdapter;
import com.ukao.cashregister.base.IPage;
import com.ukao.cashregister.base.MvpFragment;
import com.ukao.cashregister.base.PageWrapper;
import com.ukao.cashregister.bean.BatchlTabBean;
import com.ukao.cashregister.bean.BatchlistBean;
import com.ukao.cashregister.bean.FactoryBatchBean;
import com.ukao.cashregister.dialog.BatchDialogFragment;
import com.ukao.cashregister.eventbus.AppEvent;
import com.ukao.cashregister.eventbus.MembershipCardEvent;
import com.ukao.cashregister.listener.MyOnItemClickListener;
import com.ukao.cashregister.pesenter.BatchDetailsPesenter;
import com.ukao.cashregister.printer.PrintMiuiHelper;
import com.ukao.cashregister.printer.PrinterHelper;
import com.ukao.cashregister.printer.PrinterReceipt;
import com.ukao.cashregister.ui.MainActivity;
import com.ukao.cashregister.usbrfidreader.UsbrfidreaderHelper;
import com.ukao.cashregister.utils.CheckUsbDeviceUtils;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.DensityUtils;
import com.ukao.cashregister.utils.ImageUtils;
import com.ukao.cashregister.utils.MyDateUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.view.BatchDetailsView;
import com.ukao.cashregister.widget.ClearEditText;
import com.ukao.cashregister.widget.DividerDecoration;
import com.ukao.cashregister.widget.StateImageView;
import com.ukao.cashregister.widget.TwinklingLayout;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.bingoogolapple.qrcode.core.DisplayUtils;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;

import static com.ukao.cashregister.R.id.finish_btn;
import static com.ukao.cashregister.consts.GlobalConsts.SEND_FACTORY_PAGE_SIZE;

/**
 * 进厂批次  duanfuwe
 */
public class BatchDetailsFragment extends MvpFragment<BatchDetailsPesenter> implements BatchDetailsView{


    Unbinder unbinder;
    @BindView(R.id.m_back)
    TextView mBack;
    @BindView(R.id.m_title)
    TextView mTitle;
    @BindView(R.id.user_info_toolbar)
    Toolbar userInfoToolbar;
    @BindView(R.id.code)
    TextView code;
    @BindView(R.id.storeName)
    TextView storeName;
    @BindView(R.id.factoryName)
    TextView factoryName;
    @BindView(R.id.statusText)
    TextView statusText;
    @BindView(R.id.logisticsWorkName)
    TextView logisticsWorkName;
    @BindView(R.id.logisticsWorkTime)
    TextView logisticsWorkTime;
    @BindView(R.id.storeWorkTime)
    TextView storeWorkTime;
    @BindView(R.id.factoryWorkTime)
    TextView factoryWorkTime;
    @BindView(R.id.logisticsWork_layout)
    LinearLayout logisticsWorkLayout;

    @BindView(R.id.all_select)
    Button allSelect;
    @BindView(R.id.batchInrel_add)
    Button batchInrelAdd;
    @BindView(R.id.batchInRel_delete)
    Button batchInRelDelete;
    @BindView(R.id.fragment_arrive_shop_search1_edit)
    ClearEditText fragmentArriveShopSearch1Edit;
    @BindView(R.id.fragment_arrive_shop_search1_btn)
    Button fragmentArriveShopSearch1Btn;
    @BindView(R.id.isfinish_layout)
    LinearLayout isfinishLayout;
    @BindView(R.id.clothing_layout)
    TextView clothingLayout;
    @BindView(R.id.order_number)
    TextView orderNumber;
    @BindView(R.id.clothing_barcode)
    TextView clothingBarcode;
    @BindView(R.id.enter_time)
    TextView enterTime;
    @BindView(R.id.serve)
    TextView serve;
    @BindView(R.id.color)
    TextView color;
    @BindView(R.id.state)
    TextView state;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.twinkling_layout)
    TwinklingLayout twinklingLayout;
    @BindView(R.id.cdCode)
    ImageView cdCode;

    @BindView(R.id.move_batch)
    Button moveBatch;
    @BindView(R.id.rfidbtn)
    StateImageView rfidbtn;
    @BindView(R.id.clothing_state_layout)
    LinearLayout clothingStateLayout;
    @BindView(R.id.finish_btn)
    Button finishBtn;
    @BindView(R.id.print_btn)
    Button printBtn;

    @BindView(R.id.total_number)
    TextView totalNumber;
    @BindView(R.id.sortingText)
    TextView sortingText;
    @BindView(R.id.delete_btn)
    Button deleteBtn;


    private BatchDetailsAdapter matchDetailsAdapter;
    private List<BatchlistBean.ListBean> poiIData = new ArrayList<>();
    private String id;
    private List<BatchlistBean.ListBean> mData;

    private boolean isfinish;
    private PageWrapper mPageWrapper;
    private List<BatchlistBean.ListBean> mDeleteData = new ArrayList<>();
    private FactoryBatchBean mFactoryBathDetails;
    private List<BatchlistBean.ListBean> productData = new ArrayList<>();
    private String productIds;
    private int totalCount;
    private int productCnt;

    public static BatchDetailsFragment newInstance(String param1, boolean isfinish, int productCnt) {
        BatchDetailsFragment fragment = new BatchDetailsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putBoolean(ARG_PARAM2, isfinish);
        args.putInt(ARG_PARAM3, productCnt);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            id = getArguments().getString(ARG_PARAM1);
            isfinish = getArguments().getBoolean(ARG_PARAM2, false);
            productCnt = getArguments().getInt(ARG_PARAM3);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_batch_details, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initListener();
        return view;
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        mvpPresenter.orderProductDetail(_mActivity, id);
        twinklingLayout.startRefresh();

    }

    @Override
    protected void initView() {
        if (isfinish) {
            clothingStateLayout.setPadding(0, DensityUtils.dip2px(_mActivity, 20), 0, 0);
            isfinishLayout.setVisibility(View.GONE);
            finishBtn.setVisibility(View.GONE);
            printBtn.setVisibility(View.VISIBLE);
        } else {
            UsbrfidreaderHelper.getInstance().readCardNum();
            deleteBtn.setVisibility(productCnt == 0 ? View.VISIBLE : View.GONE);
            finishBtn.setVisibility(productCnt == 0 ? View.GONE : View.VISIBLE);

        }
        fragmentArriveShopSearch1Edit.requestFocus();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
        matchDetailsAdapter = new BatchDetailsAdapter(activity, poiIData);
        matchDetailsAdapter.setbatchDetailsEnter(true);
        mRecyclerView.addItemDecoration(new DividerDecoration(getActivity(), DividerDecoration.VERTICAL_LIST));
        mRecyclerView.setAdapter(matchDetailsAdapter);
        ImageUtils.setViewWith(activity, clothingLayout, 160, 0.11f);
        ImageUtils.setViewWith(activity, orderNumber, 160, 0.14f);
        ImageUtils.setViewWith(activity, clothingBarcode, 160, 0.14f);
        ImageUtils.setViewWith(activity, enterTime, 160, 0.2f);
        ImageUtils.setViewWith(activity, serve, 160, 0.1f);
        //  ImageUtils.setViewWith(activity,color,160,0.1f);
        ImageUtils.setViewWith(activity, state, 160, 0.1f);
        ImageUtils.setViewWith(activity, money, 160, 0.1f);
        ImageUtils.setViewWith(activity, sortingText, 160, 0.1f);

        IPage page = new IPage() {

            @Override
            public void load(int geIndex, int pageSize) {

                mvpPresenter.atchInRellist(_mActivity, id, geIndex, pageSize);
            }
        };
        mPageWrapper = new PageWrapper<>(mIAdapter, page);
        page.setPageSize(SEND_FACTORY_PAGE_SIZE);
    }


    IAdapter mIAdapter = new IAdapter() {
        @Override
        public void setDataSource(List data, boolean isNextLoad) {
            matchDetailsAdapter.setDatas(data);
            twinklingLayout.setEnableLoadmore(isNextLoad);


        }

        @Override
        public void loadMoreFinish(List data, boolean isNextLoad) {
            matchDetailsAdapter.addDatas(data);
            twinklingLayout.setEnableLoadmore(isNextLoad);

        }
    };
    private OnItemClickListener OnItemClickListener = new MyOnItemClickListener()

    {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            BatchlistBean.ListBean item = (BatchlistBean.ListBean) o;
            item.setCheck(!item.isCheck());
            matchDetailsAdapter.notifyDataSetChanged();
        }
    };


    @Override
    protected BatchDetailsPesenter createPresenter() {
        return new BatchDetailsPesenter(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        UsbrfidreaderHelper.getInstance().cancelReadCardNum();
    }


    @Override
    protected void initListener() {
        super.initListener();
        twinklingLayout.setOnRefreshListener(mRefreshListenerAdapter);
        matchDetailsAdapter.setOnItemClickListener(OnItemClickListener);
        fragmentArriveShopSearch1Edit.setOnEditorActionListener(mOnEditorActionListener);

    }


    private TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) {
                addBatch();

            }

            return false;
        }
    };


    private RefreshListenerAdapter mRefreshListenerAdapter = new RefreshListenerAdapter() {
        @Override
        public void onRefresh(TwinklingRefreshLayout refreshLayout) {
            super.onRefresh(refreshLayout);

            mPageWrapper.loadPage(true);
        }

        @Override
        public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
            super.onLoadMore(refreshLayout);

            mPageWrapper.loadPage(false);

        }
    };


    @Override
    public void loadTopSuccess(FactoryBatchBean mData) {
        this.mFactoryBathDetails = mData;
        code.setText(mData.getCode());
        createQRCode(mData.getCode());
        factoryName.setText(CheckUtils.isEmptyString(mData.getFactoryName()));
        statusText.setText(CheckUtils.isEmptyString(mData.getStatusText()));
        storeName.setText(CheckUtils.isEmptyString(mData.getStoreName()));
        factoryName.setText(CheckUtils.isEmptyString(mData.getFactoryName()));
        logisticsWorkName.setText("物流人员：" + CheckUtils.isEmptyString(mData.getLogisticsWorkName()) + " " + CheckUtils.isEmptyString(mData.getLogisticsWorkPhone()));
        logisticsWorkTime.setText(CheckUtils.isNull(mData.getLogisticsWorkTime()) ? "" : MyDateUtils.formatDataTime(mData.getLogisticsWorkTime()));
        storeWorkTime.setText(CheckUtils.isNull(mData.getStoreWorkTime()) ? "" : MyDateUtils.formatDataTime(mData.getStoreWorkTime()));
        factoryWorkTime.setText(CheckUtils.isNull(mData.getFactoryWorkTime()) ? "" : MyDateUtils.formatDataTime(mData.getFactoryWorkTime()));

    }

    @Override
    public void loadlListSuccess(BatchlistBean mData) {
        this.mData = mData.getList();
        mPageWrapper.addDataSource(mData.getList(), mData.getPages());
        totalCount = mData.getTotal();
        totalNumber.setText(totalCount + "");
        setRightButtonState();

    }


    /**
     * 添加批次成功
     */
    @Override
    public void reladdSuccess(boolean isclear) {
        twinklingLayout.startRefresh();
        fragmentArriveShopSearch1Edit.setText("");
        fragmentArriveShopSearch1Edit.requestFocus();
        setRightButtonState();
    }

    /**
     * 移入批次成功
     */
    @Override
    public void moveSuccess() {
        for (int i = 0; i < productData.size(); i++) {
            poiIData.remove(productData.get(i));
            totalCount = totalCount - 1;
        }
        matchDetailsAdapter.notifyDataSetChanged();
        totalNumber.setText(totalCount + "");
        setRightButtonState();

    }

    public void setRightButtonState() {
        if (!isfinish) {
            deleteBtn.setVisibility(totalCount== 0 ? View.VISIBLE : View.GONE);
            finishBtn.setVisibility(totalCount == 0 ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * 移除
     */
    @Override
    public void deleteSuccess(String message) {
        T.show(message);
        if (CheckUtils.isEmpty(mDeleteData)) return;
        for (BatchlistBean.ListBean mitem : mDeleteData) {
            totalCount = totalCount - 1;
            matchDetailsAdapter.getDatas().remove(mitem);
        }

        matchDetailsAdapter.notifyDataSetChanged();
        totalNumber.setText(totalCount + "");
        setRightButtonState();
    }


    @Override
    public void loadFail(String message) {
        T.show(message);
    }

    @Override
    public void batchFinish(String message) {
        isfinish=true;
        finishBtn.setVisibility(View.GONE);
        printBtn.setVisibility(View.VISIBLE);
        isfinishLayout.setVisibility(View.GONE);
        UsbrfidreaderHelper.getInstance().cancelReadCardNum();
        T.show(message);
    }



    @Override
    public void refreshFinish() {

        twinklingLayout.finishLoadmore();
        twinklingLayout.finishRefreshing();
    }

    @Override
    public void deleteBatchSuccess(String message) {
        deleteBtn.setVisibility(View.GONE);
        isfinishLayout.setVisibility(View.GONE);
        T.show(message);
    }

    @OnClick({R.id.fragment_arrive_shop_search1_btn, R.id.m_back, R.id.all_select, R.id.batchInrel_add, R.id.batchInRel_delete,
            R.id.move_batch, finish_btn, R.id.print_btn,R.id.delete_btn,R.id.rfidbtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case  R.id.rfidbtn :
                UsbrfidreaderHelper.getInstance().readCardNum();
                break;
            case   R.id.delete_btn:
                mvpPresenter.batchIndelete(_mActivity,id);
                break;
            case finish_btn:
                mvpPresenter.atchIncomplete(_mActivity, id);
                break;

            case R.id.fragment_arrive_shop_search1_btn:
                addBatch();

                break;
            case R.id.print_btn: /*打印袋号*/
                if (CheckUtils.isNull(mFactoryBathDetails))return;
                BatchlTabBean.ListBean mitem = new BatchlTabBean.ListBean();
                mitem.setCode(mFactoryBathDetails.getCode());
                mitem.setProductCnt(mFactoryBathDetails.getProductCnt());
                mitem.setAnnexCnt(mFactoryBathDetails.getAnnexCnt());
                mitem.setStoreName(mFactoryBathDetails.getStoreName());
                mitem.setStoreAddrDesc(mFactoryBathDetails.getStoreAddrDesc());
                mitem.setStoreRegionalDesc(mFactoryBathDetails.getStoreRegionalDesc());
                mitem.setCreateTime(mFactoryBathDetails.getCreateTime());

                if (CheckUtils.isMIUIDevices() && !CheckUtils.isNull(mFactoryBathDetails)) {
                    PrintMiuiHelper.batchPrinting(MainActivity.getPrintService(), 0, mitem);
                } else if (CheckUsbDeviceUtils.isReceipt() && !CheckUtils.isNull(mFactoryBathDetails)) {
                    GpDevice mDevice = new GpDevice();

                    PrinterReceipt.getInstance().printGpBatch(mitem, 0, mDevice);
                }

                break;
            case R.id.m_back:
                finish();
                break;
            case R.id.all_select:

                int checkCount = 0;
                for (BatchlistBean.ListBean mDataBean : poiIData) {
                    if (mDataBean.isCheck()) {
                        checkCount = checkCount + 1;
                    }

                }
                for (BatchlistBean.ListBean mDataBean : poiIData) {
                    if (checkCount == poiIData.size()) {/*都勾选了*/

                        mDataBean.setCheck(false);
                    } else {

                        mDataBean.setCheck(true);
                    }
                }

                matchDetailsAdapter.notifyDataSetChanged();


                break;
            case R.id.batchInrel_add:


                BatchDialogFragment mAddBatchDialog = new BatchDialogFragment();
                Bundle mAddBundle = new Bundle();
                mAddBundle.putString(ARG_PARAM1, resources.getString(R.string.add_clothing));
                mAddBatchDialog.setArguments(mAddBundle);
                mAddBatchDialog.show(getChildFragmentManager(), BatchDialogFragment.class.getName());


                break;
            case R.id.move_batch:
                StringBuffer mStringBuffer = new StringBuffer();
                productData.clear();
                for (BatchlistBean.ListBean item : poiIData) {
                    if (item.isCheck()) {
                        productData.add(item);
                        mStringBuffer.append(item.getProductId()).append(",");

                    }

                }
                if (mStringBuffer.length() == 0) return;
                productIds = mStringBuffer.deleteCharAt(mStringBuffer.length() - 1).toString();
                BatchDialogFragment mMoveBatchDialog = new BatchDialogFragment();
                Bundle mBundle = new Bundle();
                mBundle.putString(ARG_PARAM1, resources.getString(R.string.move_batch));
                mBundle.putString(ARG_PARAM2, id);
                mMoveBatchDialog.setArguments(mBundle);
                mMoveBatchDialog.show(getChildFragmentManager(), BatchDialogFragment.class.getName());
                break;

            case R.id.batchInRel_delete:
                mDeleteData.clear();
                StringBuffer mStringBuffers = new StringBuffer();
                for (BatchlistBean.ListBean mDataBean : poiIData) {
                    if (mDataBean.isCheck()) {
                        mStringBuffers.append(mDataBean.getId()).append(",");
                        mDeleteData.add(mDataBean);
                    }

                }

                if (mStringBuffers.length() != 0) {
                    String productId = mStringBuffers.deleteCharAt(mStringBuffers.length() - 1).toString();
                    mvpPresenter.BatchInReldelete(_mActivity, productId);

                }

                break;

        }
    }

    private void addBatch() {
        String scanCode = getText(fragmentArriveShopSearch1Edit);
        if (CheckUtils.isEmpty(scanCode)) return;
        fragmentArriveShopSearch1Edit.setText("");
        fragmentArriveShopSearch1Edit.requestFocus();
        hideSoftInput();
        mvpPresenter.BatchInReladd(_mActivity, id, "", scanCode);
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(AppEvent event) {
        switch (event.getMessage()) {
            case addbatch:
                String addid = (String) event.getData();
                if (!CheckUtils.isEmpty(addid))
                    mvpPresenter.BatchInReladd(_mActivity, id, addid, "");

                break;
            case movebatch:
                String moveId = (String) event.getData();
                if (!CheckUtils.isEmpty(moveId) && !CheckUtils.isEmpty(productIds))
                    mvpPresenter.batchshift(_mActivity, moveId, productIds);

                break;
        }

    }


    @Subscribe
    public void onEvent(MembershipCardEvent event) {

        switch (event.getMessage()) {
            case add:/*成功*/
                String rfidSecretCard = (String) event.getData();
                fragmentArriveShopSearch1Edit.setText(rfidSecretCard);
                addBatch();
                break;


        }
    }


    private void createQRCode(String code) {
        if (CheckUtils.isEmpty(code))return;
        QRCodeEncoder.encodeQRCode(code, DisplayUtils.dp2px(_mActivity, 150), new QRCodeEncoder.Delegate() {

            @Override
            public void onEncodeQRCodeSuccess(Bitmap bitmap) {
                cdCode.setImageBitmap(bitmap);
            }


            @Override
            public void onEncodeQRCodeFailure() {
                T.show("生成二维码失败");
            }
        });
    }

}
